package com.zja.servlet;
/**
 * @author JA
 * @date: 2025/5/2
 * description:
 */

import com.zja.model.User;
import com.zja.service.Impl.UserServiceImpl;
import com.zja.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.Timestamp;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private final UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");

        if (userService.findByUsername(username) != null) {
            req.setAttribute("msg", "用户名已存在！");
            req.getRequestDispatcher("register.jsp").forward(req, resp);
            return;
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setRole("user");
        user.setCreateTime(new Timestamp(System.currentTimeMillis()));
        user.setUpdateTime(new Timestamp(System.currentTimeMillis()));

        boolean success = userService.register(user);
        if (success) {
            resp.sendRedirect("login.jsp");
        } else {
            req.setAttribute("msg", "注册失败，请重试！");
            req.getRequestDispatcher("register.jsp").forward(req, resp);
        }
    }

}
